package com.bing.services.impl;

import com.bing.entity.Weather;
import com.bing.services.JSService;
import com.bing.utils.JsoupUtil;
import com.bing.utils.UtilFactory;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Created by kaibb on 16-1-3.
 */

@Component
public class JSServiceImpl implements JSService {
    private static final Logger LOGGER = LoggerFactory.getLogger(JSServiceImpl.class);
    @Value("${env.baidu.ak}")
    private String baiduAK;
    private static final String baiDuWeatherAPI = "http://api.map.baidu.com/telematics/v3/weather?output=json&ak=%s&location=%s";


    @Override
    public Weather getWeather(double longitude, double latitude) {
        Weather weather = new Weather();
        String location = longitude + "," + latitude;
        String url = String.format(baiDuWeatherAPI, baiduAK, location);
        try {
            Document document = JsoupUtil.getDocument(url);
            Map json = UtilFactory.GSON.fromJson(document.text(), Map.class);
            Map results = (Map) ((List) json.get("results")).get(0);
            String currentCity = (String) results.get("currentCity");
            weather.setLocation(currentCity);
            Map weather_data = (Map) (((List) results.get("weather_data"))).get(0);
            String weathers = weather_data.get("weather").toString() + weather_data.get("temperature").toString();
            weather.setWeather(weathers);
        } catch (Exception e) {
            LOGGER.error("抓取天气失败.", e);
        }
        LOGGER.info("位置:{},天气:{}", weather.getLocation(), weather.getWeather());
        return weather;
    }
}
